package com.im.config;

import com.im.interceptor.JwtInterceptor;
import com.im.service.JwtExcludePathService;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * 注册 JWT 拦截器 & 动态加载数据库中的放行路径
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private JwtInterceptor jwtInterceptor;
    @Autowired
    private JwtExcludePathService jwtExcludePathService;
    private List<String> excludePaths;

    /**
     * **应用启动时从数据库加载放行路径**
     */
    @PostConstruct
    public void loadExcludePaths() {
        excludePaths = jwtExcludePathService.getAllExcludePaths();
        System.out.println("✅动态加载JWT放行路径: " + excludePaths);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/**") // **拦截所有请求**
                .excludePathPatterns(excludePaths); // **从数据库加载的路径放行**
    }

    /**
     * **手动触发刷新放行路径**
     */
    public void reloadExcludePaths() {
        loadExcludePaths();
    }

    //设置静态资源映射
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 添加静态资源映射规则
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        //配置 knife4j 的静态资源请求映射地址
        registry.addResourceHandler("/doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

}
